package com.example.service;

import com.example.dao.UserDao;
import com.example.entity.Role;
import com.example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class MyUserDetailService implements UserDetailsService, UserDetailsPasswordService {
    private final UserDao userDao;

//    @Autowired
//    private BCryptPasswordEncoder bCryptPasswordEncoder;

//    public MyUserDetailService(UserDao userDao, BCryptPasswordEncoder bCryptPasswordEncoder) {
    public MyUserDetailService(UserDao userDao) {
//        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
        this.userDao = userDao;
    }

//    @Autowired
//    public MyUserDetailService(UserDao userDao) {
//        this.userDao = userDao;
//    }

//    @Autowired
//    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = this.userDao.loadUserByUsername(username);
//        user.setPassword("{root}123");
//        如果代码中return new BCryptPasswordEncoder();处使用了，则这里写写代码就不需要写为{bcrypt}xxx了
        user.setPassword("$2a$10$524IPQD.m47dXXL363YCjeYEysC2/aWAXRp9noqwTCmiAX3Qjgb4i");
        user.setUsername("admin");
        if (ObjectUtils.isEmpty(user)) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
//        String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword());
//        user.setPassword(encodedPassword);
//        查询权限信息，将其设置给用户
        Integer id = user.getId();
        List<Role> roles = userDao.getRolesByUserId(id);
        user.setRoles(roles);
        return user;
    }

    /**
     * 实现用户认证成功后，将数据库中的老密码更新为一种新的加密方式。默认使用DelegatingPasswordEncoder，默认使用相对最安全的加密方式Bcrypt--->Cxxx，会自动变化
     * @param user the user to modify the password for
     * @param newPassword the password to change to, encoded by the configured
     * {@code PasswordEncoder}
     * @return
     */
    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        Integer result = userDao.updatePassword(user.getUsername(), newPassword);
        if (result == 1) {
            User userT = (User) user;
            userT.setPassword(newPassword);
        }
        return user;
    }
}
